"""
后台管理视图
处理系统配置、操作日志等相关的API请求
"""

from rest_framework import status, generics, permissions, filters
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.db.models import Count
from django.shortcuts import get_object_or_404
from django.db import transaction

from .models import SystemConfig, OperationLog, AdminPermission
from .serializers import (
    SystemConfigSerializer, OperationLogSerializer, AdminPermissionSerializer
)
from utils.response import success_response, error_response, paginated_response
from rest_framework.permissions import IsAdminUser


class SystemConfigListView(generics.ListCreateAPIView):
    """
    系统配置列表视图
    """
    permission_classes = [IsAdminUser]
    serializer_class = SystemConfigSerializer
    queryset = SystemConfig.objects.filter(is_active=True)
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['key', 'description']
    ordering_fields = ['config_type', 'key']
    ordering = ['config_type', 'key']

    def list(self, request, *args, **kwargs):
        """获取系统配置列表"""
        queryset = self.get_queryset()

        # 类型筛选
        config_type = self.request.query_params.get('type')
        if config_type:
            queryset = queryset.filter(config_type=config_type)

        serializer = self.get_serializer(queryset, many=True)
        return success_response(
            data=serializer.data,
            message="获取系统配置列表成功"
        )

    def create(self, request, *args, **kwargs):
        """创建系统配置"""
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 201,
                'message': "创建系统配置成功",
                'data': serializer.data,
                'success': True
            }, status=status.HTTP_201_CREATED)
        else:
            return error_response(
                message="创建系统配置失败",
                data=serializer.errors,
                status_code=status.HTTP_400_BAD_REQUEST
            )


class SystemConfigDetailView(generics.RetrieveUpdateAPIView):
    """
    系统配置详情视图
    """
    permission_classes = [IsAdminUser]
    serializer_class = SystemConfigSerializer
    queryset = SystemConfig.objects.all()

    def retrieve(self, request, *args, **kwargs):
        """获取系统配置详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(
            data=serializer.data,
            message="获取系统配置详情成功"
        )

    def update(self, request, *args, **kwargs):
        """更新系统配置"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid():
            serializer.save()
            return success_response(
                data=serializer.data,
                message="更新系统配置成功"
            )
        else:
            return error_response(
                message="更新系统配置失败",
                data=serializer.errors,
                status_code=status.HTTP_400_BAD_REQUEST
            )


class OperationLogListView(generics.ListAPIView):
    """
    操作日志列表视图
    """
    permission_classes = [IsAdminUser]
    serializer_class = OperationLogSerializer
    queryset = OperationLog.objects.all()
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['operator__username', 'description', 'ip_address']
    ordering_fields = ['created_at', 'operator', 'module']
    ordering = ['-created_at']

    def list(self, request, *args, **kwargs):
        """获取操作日志列表"""
        queryset = self.get_queryset()

        # 模块筛选
        module = self.request.query_params.get('module')
        if module:
            queryset = queryset.filter(module=module)

        # 操作类型筛选
        operation_type = self.request.query_params.get('operation_type')
        if operation_type:
            queryset = queryset.filter(operation_type=operation_type)

        # 时间范围筛选
        start_time = self.request.query_params.get('start_time')
        end_time = self.request.query_params.get('end_time')
        if start_time and end_time:
            queryset = queryset.filter(created_at__range=[start_time, end_time])
        elif start_time:
            queryset = queryset.filter(created_at__gte=start_time)
        elif end_time:
            queryset = queryset.filter(created_at__lte=end_time)

        # 分页
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 20))
        start = (page - 1) * page_size
        end = start + page_size

        total_count = queryset.count()
        logs = queryset[start:end]

        serializer = self.get_serializer(logs, many=True)
        return paginated_response(
            data=serializer.data,
            count=total_count,
            page=page,
            page_size=page_size
        )


class AdminPermissionListView(generics.ListAPIView):
    """
    管理员权限列表视图
    """
    permission_classes = [IsAdminUser]
    serializer_class = AdminPermissionSerializer
    queryset = AdminPermission.objects.filter(is_active=True)
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['name', 'code', 'description']
    ordering_fields = ['module', 'name']
    ordering = ['module', 'name']

    def list(self, request, *args, **kwargs):
        """获取管理员权限列表"""
        queryset = self.get_queryset()

        # 模块筛选
        module = self.request.query_params.get('module')
        if module:
            queryset = queryset.filter(module=module)

        serializer = self.get_serializer(queryset, many=True)
        return success_response(
            data=serializer.data,
            message="获取管理员权限列表成功"
        )
